package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.entity.BaseAttrValue;
import com.atguigu.gmall.product.service.BaseAttrValueService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.product.entity.BaseAttrInfo;
import com.atguigu.gmall.product.service.BaseAttrInfoService;
import com.atguigu.gmall.product.mapper.BaseAttrInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【base_attr_info(属性表)】的数据库操作Service实现
* @createDate 2023-11-01 15:32:53
*/
@Service
public class BaseAttrInfoServiceImpl extends ServiceImpl<BaseAttrInfoMapper, BaseAttrInfo> implements BaseAttrInfoService {

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper ;

    @Autowired
    private BaseAttrValueService baseAttrValueService ;

    @Override
    public List<BaseAttrInfo> findByCategoryId(Long c1Id, Long c2Id, Long c3Id) {
        return baseAttrInfoMapper.findByCategoryId(c1Id , c2Id , c3Id) ;
    }

    @Override
    @Transactional
    public void saveBaseAttrInfo(BaseAttrInfo baseAttrInfo) {

        Long attrId = baseAttrInfo.getId();
        if(attrId == null) {

            // 保存平台属性名称数据
            this.save(baseAttrInfo) ;

            // 保存平台属性值数据
            List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();

            /**
             * stream流中map方法作用：对流中的元素数据类型做转换
             * 需求：从List<BaseAttrValue>中获取每一个元素的valueName的值
             */
            attrValueList = attrValueList.stream().map(baseAttrValue -> {
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                return baseAttrValue;
            }).collect(Collectors.toList());
            baseAttrValueService.saveBatch(attrValueList) ;

        }else  {

            // 修改平台属性名
            this.updateById(baseAttrInfo) ;

            // 修改平台属性值
            LambdaQueryWrapper<BaseAttrValue> lambdaQueryWrapper = new LambdaQueryWrapper<>() ;
            lambdaQueryWrapper.eq(BaseAttrValue::getAttrId , attrId) ;
            baseAttrValueService.remove(lambdaQueryWrapper) ;

            // 保存平台属性值数据
            List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();

            /**
             * stream流中map方法作用：对流中的元素数据类型做转换
             * 需求：从List<BaseAttrValue>中获取每一个元素的valueName的值
             */
            attrValueList = attrValueList.stream().map(baseAttrValue -> {
                baseAttrValue.setAttrId(attrId);
                return baseAttrValue;
            }).collect(Collectors.toList());
            baseAttrValueService.saveBatch(attrValueList) ;
        }

    }

}




